package com.example.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@Slf4j
@EnableAsync
public class CommonThreadPoolConfig {

    private int corePoolSize = 5;

    private int maxPoolSize = 50;

    private int queueSize = 50;

    private String prefix = "common-thread-pool";

    @Bean("commonExecutor")
    public Executor commonExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 配置队列大小
        executor.setQueueCapacity(queueSize);
        // 配置线程池中线程的名称前缀
        executor.setThreadNamePrefix(prefix);
        // 配置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 执行初始化
        executor.initialize();
        log.info("corePoolSize:{}; maxPoolSize:{}; queueCapacity:{}, threadNamePrefix:{}", corePoolSize, maxPoolSize, queueSize, prefix);
        return executor;
    }
}